#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import pycurl
import StringIO
from xml.dom import minidom
from urllib import urlencode

from config import *

friendsTimelineUrl = 'http://api.fanfou.com/statuses/friends_timeline.xml'
updateUrl = 'http://api.fanfou.com/statuses/update.xml'
userTimelineUrl = 'http://api.fanfou.com/statuses/user_timeline.xml'
publicTimelineUrl = 'http://api.fanfou.com/statuses/public_timeline.xml'

def fetchUrl( url, uName, uPwd ):
        c = pycurl.Curl()
        c.setopt(pycurl.URL, url)
        c.setopt(pycurl.USERPWD, uName+':'+uPwd)
        b = StringIO.StringIO()
        c.setopt(pycurl.WRITEFUNCTION, b.write)
        c.perform()
        xmldoc = minidom.parseString(b.getvalue())
        b.close()
        return xmldoc

def showTL(xmlTL):
        statuslist = xmlTL.getElementsByTagName('status')
        for status in statuslist:
		        user = status.getElementsByTagName('user')
		        userName = user[0].getElementsByTagName('name')
		        userText = status.getElementsByTagName('text')
		        print userName[0].firstChild.data, 'say:', userText[0].firstChild.data

def updateMsg(url, uName, uPwd, msg):
        sendMsg = {}
        #sendmsg['status'] = msg.encode('utf-8')
	sendMsg['status'] = msg
        c = pycurl.Curl()
        c.setopt(pycurl.URL, url)
        c.setopt(pycurl.USERPWD, uName+':'+uPwd)
        c.setopt(pycurl.POST, 1)
        c.setopt(pycurl.POSTFIELDS, urlencode(sendMsg))
        c.perform()

def getXmlFriendTL():
	return fetchUrl(friendsTimelineUrl, username, passwd)

def getXmlPublicTL():
	return fetchUrl(publicTimelineUrl, username, passwd)

def showPublicTL():
        showTL(getXmlPublicTL())

def showFriendTL():
        showTL(getXmlFriendTL())


if __name__ == '__main__':
        while 1:
		op = raw_input('1.查看timeline\n2.查看公共timeline\n3.更新消息\n输入选择')
		if int(op) == 1:
			showFriendTL()
		elif int(op) == 2:
			showPublicTL()
		elif int(op) == 3:
			Msg = raw_input('输入状态：')
			updateMsg(updateUrl, username, passwd, Msg)
			
